<?php

namespace App\Http\Controllers\API;

use App\Models\Users\UserLoginLog;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Validator;

class PassportController extends Controller
{

    public $successStatus = 200;

    /**
     * login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login()
    {
        $auth  = Auth::attempt (['user_email' => request ('username'), 'password' => request ('password')]);
        $auth2 = Auth::attempt (['user_mobile' => request ('username'), 'password' => request ('password')]);
        if ($auth || $auth2) {
            $user             = Auth::user ();
            $uuid             = UserLoginLog::create ([
                'login_type'  => UserLoginLog::LOGIN_TYPE_WEB_LOGIN,
                'log_content' => __ ('用户接口登录，获取token值')
            ]);
            $success['locale'] =App::getLocale();
            $success['uuid']  = $uuid;
            $success['token'] = $user->createToken ('MyApp', ['web-api'])->accessToken;


            return response ()->json (['success' => $success], $this->successStatus);
        }

        return response ()->json (['error' => 'Unauthorised'], 401);
    }

    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make ($request->all (), [
            'user_name'  => 'required',
            'user_email' => 'required|email',
            'password'   => 'required',
            'c_password' => 'required|same:password',
        ]);

        if ($validator->fails ()) {
            return response ()->json (['error' => $validator->errors ()], 401);
        }

        $input             = $request->all ();
        $input['password'] = bcrypt ($input['password']);
        $user              = User::create ($input);
        $success['token']  = $user->createToken ('MyApp')->accessToken;
        $success['name']   = $user->name;

        return response ()->json (['success' => $success], $this->successStatus);
    }

    /**
     * details api
     *
     * @return \Illuminate\Http\Response
     */
    public function getDetails()
    {
        $user = Auth::user ();

        return response ()->json (['success' => $user], $this->successStatus);
    }
}